package com.ndhutu.ee.util.pay.apple;

import com.alibaba.fastjson.JSONObject;
import com.ndhutu.ee.util.http.OKHttpUtil;
import com.ndhutu.ee.util.pay.Notify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 苹果支付工具类
 * @Author Shane
 * @Date 2019/12/13 10:34
 * @param
 * @return
 **/
public class ApplePayUtil {
    private static Logger log = LoggerFactory.getLogger(ApplePayUtil.class);

    public static String sendPost(String url, String param) {
        StringBuilder sb = new StringBuilder();
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            sb = new StringBuilder();
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static Boolean notify(ApplePayConfig config, String receipt, Notify notify) throws Exception{
        Map<String, String> params = new HashMap<String, String>();
        params.put("receipt-data", receipt);
        log.info("客户端凭证：" + receipt);

//        Map<String, String> headers = new HashMap<String, String>();
//        headers.put("content-type", "text/json");
//        headers.put("Proxy-Connection", "Keep-Alive");
//        headers.put("accept", "*/*");
//        headers.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//        String result = OKHttpUtil.post(config.getPayVerifyUrl(), params, headers);
        String result = sendPost(config.getPayVerifyUrl(), "{\"receipt-data\":\"" + receipt + "\"}");
        log.info("苹果内购校验结果：" + result);

        Map<String, Object> validate = JSONObject.parseObject(result, Map.class);
        if(Integer.parseInt(validate.get("status")+"") == 0){
            //验证成功
            Map<String, Object> receiptMap = (Map)validate.get("receipt");

            List<Receipt> receipts = new ArrayList<Receipt>();

            List<Map<String, Object>> in_app = (List<Map<String, Object>>) receiptMap.get("in_app");
            if(in_app == null){
                Receipt r = JSONObject.parseObject(JSONObject.toJSONString(receiptMap), Receipt.class);
                receipts.add(r);
            }else{
                for(Map<String, Object> app : in_app){
                    Receipt r = JSONObject.parseObject(JSONObject.toJSONString(app), Receipt.class);
                    receipts.add(r);
                }
            }

            for(Receipt r : receipts){
                String orderNumber = r.getTransaction_id();

                String pid = r.getProduct_id();
                Integer amount = Integer.parseInt(pid.substring(pid.lastIndexOf("_")+1));

                //统一回调
                notify.handleNotify(orderNumber, amount);

                log.info("订单" + orderNumber + "apple支付回调成功");
            }

            return true;
        }

        return false;
    }

    /**
     * 苹果消费凭证校验
     * @Author Shane
     * @Date 2019/12/23 15:48
     * @param
     * @return
     **/
    public static List<Receipt> verifyCredential(ApplePayConfig config, String receipt) throws Exception{
        Map<String, String> params = new HashMap<String, String>();
        params.put("receipt-data", receipt);
        log.info("客户端凭证：" + receipt);

//        Map<String, String> headers = new HashMap<String, String>();
//        headers.put("content-type", "text/json");
//        headers.put("Proxy-Connection", "Keep-Alive");
//        headers.put("accept", "*/*");
//        headers.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//        String result = OKHttpUtil.post(config.getPayVerifyUrl(), params, headers);
        String result = sendPost(config.getPayVerifyUrl(), "{\"receipt-data\":\"" + receipt + "\"}");
        log.info("苹果内购校验结果：" + result);

        Map<String, Object> validate = JSONObject.parseObject(result, Map.class);
        if(Integer.parseInt(validate.get("status")+"") == 0){
            //验证成功
            Map<String, Object> receiptMap = (Map)validate.get("receipt");

            List<Receipt> receipts = new ArrayList<Receipt>();

            List<Map<String, Object>> in_app = (List<Map<String, Object>>) receiptMap.get("in_app");
            if(in_app == null){
                Receipt r = JSONObject.parseObject(JSONObject.toJSONString(receiptMap), Receipt.class);
                receipts.add(r);
            }else{
                for(Map<String, Object> app : in_app){
                    Receipt r = JSONObject.parseObject(JSONObject.toJSONString(app), Receipt.class);
                    receipts.add(r);
                }
            }

            return receipts;
        }
        return null;
    }
}
